package com.penghaonan.appframework.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.penghaonan.appframework.AppDelegate;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class ShareUtils {

    private static final Map<String, String> mimeMap = new HashMap<>();

    static {
        mimeMap.put("apk", "application/vnd.android.package-archive");
        mimeMap.put("png", "image/png");
        mimeMap.put("jpg", "image/jpeg");
        mimeMap.put("mp4", "video/mp4");
    }

//    public static void shareFile(File file) {
//        if (file == null) {
//            return;
//        }
//        Intent intent = new Intent(Intent.ACTION_SEND);
//        intent.putExtra(Intent.EXTRA_STREAM, FileUtils.uriFromFile(file));
//        String suffix = FileUtils.getSuffix(file);
//        String mime = mimeMap.get(suffix);
//        intent.setType(TextUtils.isEmpty(mime) ? "*/*" : mime);
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        boolean res = AppDelegate.startActivity(intent);
//        if (!res) {
//            ToastUtils.showToast(R.string.activity_open_failed);
//        }
//    }

    public static void shareFile(Context context, File file) {
        if (file == null || !file.exists()) {
            return;
        }
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, AppDelegate.getApp().getPackageName() + ".fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        if (Logger.isDebug()) {
            if (uri != null) {
                Logger.i("Share Uri:" + uri.toString());
            }
        }
        shareIntent.setType("application/vnd.android.package-archive");//此处可发送多种文件
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        shareIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        shareIntent.setDataAndType(uri, context.getContentResolver().getType(uri));

        Intent chooser = Intent.createChooser(shareIntent, "Share File");
        context.startActivity(chooser);
    }
}
